import { DATA_SORT_DESC } from "../../AppConstants/constants";

class DBQueryBuilder {
  getCondition() {
    return this.condition;
  }

  setCondition(value = {}) {
    this.condition = value;
    return this;
  }

  getFields() {
    return this.fields;
  }

  setFields(value = []) {
    this.fields = value;
    return this;
  }

  getPage() {
    return this.page;
  }

  setPage(value = 1) {
    this.page = value;
    return this;
  }

  getPerpage() {
    return this.perpage;
  }

  setPerpage(value = 10) {
    this.perpage = value;
    return this;
  }

  getLimit() {
    return this.perpage;
  }

  getSort() {
    return this.sort;
  }

  setSort(value = { createdAt: DATA_SORT_DESC }) {
    this.sort = value;
    return this;
  }

  getSkip() {
    return this.skip;
  }

  setSkip(value) {
    this.skip = value;
  }

  constructor(values = {}) {
    values = Object.assign(
      {
        fields: [],
        page: 1,
        perpage: 10,
        sort: { createdAt: DATA_SORT_DESC },
        condition: {}
      },
      values
    );
    this.fields = values.fields;
    this.page = values.page;
    this.perpage = values.perpage;
    this.sort = values.sort;
    this.skip = this.toSkip();
    this.condition = values.condition;
  }

  toPage() {
    return this.skip / this.limit + 1;
  }

  toSkip() {
    return (this.page - 1) * this.limit;
  }

  toObject() {
    return {
      fields: this.fields,
      page: this.page,
      perpage: this.perpage,
      sort: this.sort,
      skip: this.skip,
      condition: this.condition
    };
  }

  /**
   * geta JSON string representation of the struct.
   *
   * @return {string}
   */
  toJSON(replacer, space) {
    return JSON.stringify(this.toObject(), replacer, space);
  }
}

export { DBQueryBuilder };
export default DBQueryBuilder;
